package com.fs.jzzn.controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.fs.base.param.SysConstant;
import com.fs.base.repository.SqlRepository;
import com.fs.base.vo.DataGrid;
import com.fs.base.vo.JsonResponse;
import com.fs.base.vo.SysPath;
import com.fs.jzzn.pojo.Contract;
import com.fs.jzzn.pojo.Expense;
import com.fs.jzzn.pojo.Income;
import com.fs.jzzn.pojo.Invoice;
import com.fs.jzzn.repository.ContractRepository;
import com.fs.jzzn.repository.ExpenseRepository;
import com.fs.jzzn.repository.IncomeRepository;
import com.fs.jzzn.repository.InvoiceRepository;
/**
 * 统计业务
 * @author 10424
 *
 */
@Controller
@RequestMapping("/console/statistics/rewrite")
public class StatisticsController {
	private static final Logger log = Logger.getLogger(StatisticsController.class);
	@Autowired private IncomeRepository incomeRepository;
	@Autowired private ExpenseRepository expenseRepository;
	@Autowired private InvoiceRepository invoiceRepository;
	@Autowired private ContractRepository contractRepository;
	@Autowired private SqlRepository sqlRepository;
	
	@RequestMapping("/{pageName}")
	public String pageName(@PathVariable String pageName, HttpServletRequest req){
		return SysPath.BACK_PATH.concat("/statistics/").concat(pageName);
	}
	
	/**
	 * 支出统计
	 * @param req
	 * @return
	 */
	@RequestMapping("expense")
	public String expense(HttpServletRequest req,String type){
		return SysPath.BACK_PATH.concat("/statistics/expense_chart_"+type);
	}
	
	/**
	 * 收入统计列表
	 * @param contractNo
	 * @return
	 */
	@RequestMapping("/incomelist")
	@ResponseBody
	public DataGrid incomelist(String contractNo){
		try {
			List<Income> incomeList = incomeRepository.findBycontractNo(contractNo);
			return DataGrid.gridBuilder(incomeList);
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e.getMessage());
			return new DataGrid();
		}
	}
	
	
	/**
	 * 支出统计列表
	 * @param contractNo
	 * @return
	 */
	@RequestMapping("/expenselist")
	@ResponseBody
	public DataGrid expenselist(String contractNo){
		try {
			List<Expense> expenseList = expenseRepository.findBycontractNo(contractNo);
			return DataGrid.gridBuilder(expenseList);
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e.getMessage());
			return new DataGrid();
		}
	}
	
	/**
	 * 发票统计列表
	 * @param contractNo
	 * @return
	 */
	@RequestMapping("/invoicelist")
	@ResponseBody
	public DataGrid invoicelist(String contractNo){
		try {
			List<Invoice> invoiceList = invoiceRepository.findBycontractNo(contractNo);
			return DataGrid.gridBuilder(invoiceList);
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e.getMessage());
			return new DataGrid();
		}
	}
	
	@ResponseBody
	@RequestMapping("contractlist")
	public Object getChildContractList(DataGrid grid,HttpServletRequest request) {
		try {
			if(grid==null) grid = new DataGrid();
			String contractNo = request.getParameter("contractNo");
			if(StringUtils.isNotBlank(contractNo)){
				List<String> list = contractRepository.getChildContractList(contractNo);
				List<Contract> rows = contractRepository.findByContractNoIn(list);
				grid = DataGrid.gridBuilder(rows);
			}
		} catch (Exception e) {
			grid = DataGrid.gridBuilder(new ArrayList<Object>());
			e.printStackTrace();
			log.error(e.getMessage());
		}
		return grid;
	}
	
	/*
	 * 月份-组织支出统计
	 */
	/*@ResponseBody
	@RequestMapping("monthOrgExpense")
	public Object monthOrgExpense(HttpServletRequest request) {
		JSONObject json = new JSONObject();
		try {
			List<String>legendList = new ArrayList<>();
			List<JSONObject> seriesData = new ArrayList<>();
			String sql1 = "SELECT SUM(money) as total,creater_id FROM p_expense_item GROUP BY creater_id ";
			List<Object[]> costTypeList = sqlRepository.list(sql1, null, null);
			String name = null;
			int i = 1;
			for(Object[] nvs: costTypeList){
				JSONObject item = new JSONObject();
				name = nvs[1] ==null? ("未知_"+i): nvs[1].toString();
				i++;
				if(SysConstant.USERS_ID_NAME_MAP.containsKey(name)){
					name = SysConstant.USERS_ID_NAME_MAP.get(name);
				}
				item.put("name", name);
				legendList.add(name);
				
				item.put("value", nvs[0]);
				seriesData.add(item);
			}
			json.put("legendData", legendList);
			json.put("seriesData", seriesData);
			
			return JsonResponse.success(json);
			
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e.getMessage());
			return JsonResponse.error();
		}
	}*/
	
	@ResponseBody
	@RequestMapping("echart")
	public Object monthOrgExpense(HttpServletRequest request,String type) {
		JSONObject json = new JSONObject();
		try {
            String startTime = request.getParameter("startTime");
            String endTime = request.getParameter("endTime");
            List<String>legendList = new ArrayList<>();
			List<JSONObject> seriesData = new ArrayList<>();
			String sql = null;
			if("category".equals(type)){
				sql = "SELECT round(SUM(money)/10000,2) as total,cost_type FROM p_expense_item WHERE cost_type<>'合作单位支出' and cost_type<>'工程款' GROUP BY cost_type  ";
			}else if("person".equals(type)){
				sql = "SELECT round(SUM(money)/10000,2) as total,creater_id FROM p_expense_item GROUP BY creater_id ";
			}else if("income".equals(type)){
				sql = "SELECT round(SUM(money)/10000,2) as total,DATE_FORMAT(returned_date,'%Y-%m') as mon FROM p_income GROUP BY returned_date ORDER BY mon asc  " ;
			}else if("cooperation".equals(type)){
			    if(StringUtils.isBlank(startTime) && StringUtils.isBlank(endTime)){
                    sql = "SELECT round(sum(money)/10000,2) money,department name from p_expense_item WHERE cost_type = \"合作单位支出\" GROUP BY department";
                }else if(StringUtils.isBlank(startTime) && StringUtils.isNotBlank(endTime)){
                    sql = "SELECT round(sum(money)/10000,2) money,department name from p_expense_item WHERE cost_type = \"合作单位支出\"  AND cost_date <= \""+endTime+"\" GROUP BY department";
                }else if(StringUtils.isNotBlank(startTime) && StringUtils.isBlank(endTime)){
                    sql = "SELECT round(sum(money)/10000,2) money,department name from p_expense_item WHERE cost_type = \"合作单位支出\"  AND cost_date >= \""+startTime+"\" GROUP BY department";
                }else{
                    sql = "SELECT round(sum(money)/10000,2) money,department name from p_expense_item WHERE cost_type = \"合作单位支出\"  AND cost_date >= \""+startTime+"\"  AND cost_date <= \""+endTime+"\" GROUP BY department";
                }
			}else if("collect".equals(type)){
				if(StringUtils.isBlank(startTime) && StringUtils.isBlank(endTime)){
					sql = "SELECT round(sum(money)/10000,2) money,org_no FROM p_income GROUP BY org_no";
				}else if(StringUtils.isBlank(startTime) && StringUtils.isNotBlank(endTime)){
					sql = "SELECT round(sum(money)/10000,2) money,org_no FROM p_income WHERE returned_date <= \""+endTime+"\" GROUP BY org_no";
				}else if(StringUtils.isNotBlank(startTime) && StringUtils.isBlank(endTime)){
					sql = "SELECT round(sum(money)/10000,2) money,org_no FROM p_income WHERE returned_date >= \""+startTime+"\" GROUP BY org_no";
				}else{
					sql = "SELECT round(sum(money)/10000,2) money,org_no FROM p_income WHERE returned_date >= \""+startTime+"\"  AND returned_date <= \""+endTime+"\" GROUP BY org_no";
				}
			}
			List<Object[]> costTypeList = sqlRepository.list(sql, null, null);
			String name = null;
			int i = 1;
			for(Object[] nvs: costTypeList){
				JSONObject item = new JSONObject();
				name = nvs[1] ==null? ("未知_"+i): nvs[1].toString();
				i++;
				if("person".equals(type) && SysConstant.USERS_ID_NAME_MAP.containsKey(name)){
					name = SysConstant.USERS_ID_NAME_MAP.get(name);
				}else if("collect".equals(type)){
					name = SysConstant.ORG_NO_NAME_MAP.get(name);
				}
				item.put("name", name);
				legendList.add(name);
				
				item.put("value", nvs[0]);
				seriesData.add(item);
			}
			json.put("legendData", legendList);
			json.put("seriesData", seriesData);
			
			return JsonResponse.success(json);
			
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e.getMessage());
			return JsonResponse.error();
		}
	}
	
}
